package studio.wetrack.dinner.domain;

import lombok.Data;
import studio.wetrack.dinner.service.ChopsticksService;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by zhanghong on 2017/7/29.
 */
@Data
@Entity(name = "user")
public class User {
    @Id
    Long id;
    String name;
    @Column(name = "id_num")
    String idNum;
    Date birthday;
    String sex;

    @Transient
    Chopsticks chopsticks;

    @Transient
    Table sittingTable;


    @Transient
    ChopsticksService chopsticksService;


    private boolean oneBite(Dish dish){
//        boolean success = dish.eat();
        boolean success = chopsticks.takeOneShare(dish);
        if(success){
            System.out.println(name + "夹到了" + dish.getName());
        }else{
            System.out.println(name + "没有夹到" + dish.getName());
        }
        return success;
    }

    private boolean tryAndBite(){
        final List<Dish> dishes = sittingTable.getDishList();
        for (Dish dish : dishes) {
            if(oneBite(dish)){
                //吃了一口，返回
                return true;
            }
        }
        return false;
    }

    public void sitBesideTable(Table table){
        this.sittingTable = table;
    }

    public void setChopsticks(Chopsticks chopsticks){
        this.chopsticks = chopsticks;
    }
    public void startEat(){
        final Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if(!tryAndBite()) {
                    //到了这里，意味着这次没有吃一口，说明全吃完了
                    timer.cancel();
                    //把筷子释放掉
                    chopsticksService.releaseChopsticks(chopsticks);
                }

            }
        }, 1000, 1000);

    }




    public enum Sex{
        MALE,
        FEMALE,
        ;

    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", idNum='" + idNum + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", chopsticks=" + chopsticks +
                '}';
    }
}
